#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"
void HeapInit(Heap* php)
{
	assert(php);
	php->a = NULL;
	php->size = 0;
	php->capacity = 0;
}
void HeapPush(Heap* php, heapdatatype x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		heapdatatype* temp = (heapdatatype*)realloc(php->a, sizeof(heapdatatype) * newcapacity);
		if (temp == NULL)
		{
			perror("realloc fail");
		}
		php->a = temp;
		php->capacity = newcapacity;
	}
	php->a[php->size] = x;
	php->size++;
	Adjustup(php->a, php->size-1);
}
void Swap(heapdatatype* p1, heapdatatype* p2)
{
	heapdatatype tem = *p1;
	*p1 = *p2;
	*p2 = tem;
}
void Adjustup(heapdatatype* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] <a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else break;
	}

}
void AdjustDown(heapdatatype* a, int parent ,int size)
{
	int child = parent * 2 + 1;
	while (child < size)
	{
		if (child + 1 < size && a[child] > a[child + 1]) child++;
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 +1;
		}
		else
		{
			break;
		}
	}
}
void HeapPop(Heap* php)
{
	assert(php);
	assert(php->size > 0);

	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;

	AdjustDown(php->a, 0,php->size);

}
heapdatatype HeapTop(Heap* php)
{
	assert(php);
	assert(php->a);
	return php->a[0];
}
void HeapDestroy(Heap* php)
{
	assert(php);
	free(php->a);
	php->capacity = php->size = 0;
	
}
size_t Heapsize(Heap* php)
{
	assert(php);
	return php->size;
}
bool HeapEmpty(Heap* php)
{
	assert(php);
	return php->size == 0;
}

